import 'package:flutter/cupertino.dart';
import 'package:flutter_getx/app/data/db/entity/message.dart';
import 'package:flutter_getx/app/service/db_service.dart';
import 'package:flutter_getx/app/service/message_service.dart';
import 'package:flutter_getx/app/service/user_info_service.dart';
import 'package:get/get.dart';

import '../../../data/model/chat_message.dart';
import '../../../routes/app_pages.dart';

class MessageController extends GetxController {
  DBService dbService = Get.find();
  UserInfoService userInfoService = Get.find();
  TextEditingController textEditingController = TextEditingController();

  MessageService messageService = Get.find();

  ScrollController scrollController = ScrollController();

  int friendId = 0;
  String friendName = "";
  String friendUrl = "";
  bool isGroup = false;

  void scrollToBottom() {
    Future.delayed(Duration(milliseconds: 500), () {
      scrollController.jumpTo(scrollController.position.maxScrollExtent);
    });
  }

  Future<void> sendTextMessage(String txt) async {
    if (friendId == 0) {
      return;
    }
    if (!messageService.messageMap.containsKey(friendId)) {
      messageService.messageMap[friendId] = [];
    }

    messageService.messageMap[friendId]!.add(ChatMessage(
      text: txt,
      contentType: ChatContentType.text,
      messageStatus: MessageStatus.viewed,
      isSender: true,
      fromUserId: userInfoService.userInfo.value.id!,
    ));
    messageService.messageMap.refresh();
    textEditingController.clear();

    var time = DateTime.now().millisecondsSinceEpoch;
    await dbService.messageDao.insertMessage(MessageEntity(
        createAt: time,
        content: txt,
        fromUserId: userInfoService.userInfo.value.id,
        toUserId: friendId,
        contentType: 1));
    messageService.sendMessage(friendId, time, txt, this.isGroup);
    this.scrollToBottom();
  }

  @override
  void onInit() {
    print('进入uid: ' + Get.arguments.toString() + "的聊天窗口");

    friendId = Get.arguments['userId'];
    friendName = Get.arguments['user'];
    friendUrl = Get.arguments['url'];


    isGroup = Get.arguments['type'] == 2 ? true : false;

    this.scrollToBottom();
    super.onInit();
  }

  void toProfile(int uid) {
    Get.toNamed(Routes.OTHER_PROFILE, arguments: uid);
  }

  void toProfile1() {
    if (this.isGroup) {
      Get.toNamed(Routes.GROUP_INFO, arguments: friendId);
    } else {
      Get.toNamed(Routes.OTHER_PROFILE, arguments: friendId);
    }
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {}
}
